<template>
  <div>
    <p style="float: right">单位：Kpcs</p>
    <p-table
      class="table-list-container"
      :row-key="(records, index) => index"
      :columns="columns"
      :data-source="formatList"
      :pagination="false"
      bordered
      v-bind="$attrs"
      v-on="$listeners"
    >
    </p-table>
  </div>
</template>

<script>
let idKey = 0;
const totalKeys = ['bpQuantity', 'rpQuantity', 'm9Quantity', 'orderQuantity'];
export default {
  props: {
    dataSource: {
      type: Array,
      default: () => [],
    },
    total: {
      type: Array,
      default: () => [],
    },
    month: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      count: 1,
    };
  },
  computed: {
    applicationOptions() {
      return this.$store.state.dictionary.dict['application'] || {};
    },
    formatList() {
      if (this.dataSource.length === 0) {
        return;
      }
      const list = Object.keys(this.groups).map((group) => {
        const data = this.groups[group] || [];

        let total = data.reduce(
          (pre, cur) => {
            totalKeys.forEach((key) => {
              if (pre[key]) {
                pre[key] += Number(cur[key] || 0);
              } else {
                pre[key] = Number(cur[key] || 0);
              }
            });
            return pre;
          },
          { id: 'totalKey', salesGroupName: '组内汇总' }
        );
        return [...data, total];
      });
      const smallAllTotal = this.dataSource.reduce(
        (pre, cur) => {
          totalKeys.forEach((key) => {
            if (pre[key]) {
              pre[key] += Number(cur[key] || 0);
            } else {
              pre[key] = Number(cur[key] || 0);
            }
          });
          return pre;
        },
        { id: 'smallAllTotal', salesGroupName: '小片销售总计(Kpcs)' }
      );

      // const bigAllTotal = this.dataSource.reduce(
      //   (pre, cur) => {
      //     totalKeys.forEach((key) => {
      //       if (key === 'bpQuantity') {
      //         pre['bigBoardBp'] += Number(cur['bigBoardBp'] || 0);
      //       } else if (key === 'rpQuantity') {
      //         pre['bigBoardRp'] += Number(cur['bigBoardRp'] || 0);
      //       } else if (key === 'fcstQuantity') {
      //         pre['bigBoardM9'] += Number(cur['bigBoardM9'] || 0);
      //       }
      //     });
      //     return pre;
      //   },
      //   {
      //     id: 'bigAllTotal',
      //     salesGroupName: '大片销售总计(Kpcs)',
      //     bigBoardBp: 0,
      //     bigBoardRp: 0,
      //     bigBoardM9: 0,
      //   }
      // );
      // bigAllTotal.bpQuantity = Math.ceil(bigAllTotal.bigBoardBp);
      // bigAllTotal.rpQuantity = Math.ceil(bigAllTotal.bigBoardRp);
      // bigAllTotal.fcstQuantity = Math.ceil(bigAllTotal.bigBoardM9);
      // const totalRevenue = this.dataSource.reduce(
      //   (pre, cur) => {
      //     totalKeys.forEach((key) => {
      //       if (key === 'bpQuantity') {
      //         pre['totalRevenueBp'] += Number(cur['totalRevenueBp'] || 0);
      //       } else if (key === 'rpQuantity') {
      //         pre['totalRevenuerp'] += Number(cur['totalRevenuerp'] || 0);
      //       } else if (key === 'fcstQuantity') {
      //         pre['totalRevenueM9'] += Number(cur['totalRevenueM9'] || 0);
      //       }
      //     });
      //     return pre;
      //   },
      //   {
      //     id: 'totalRevenue',
      //     salesGroupName: '营收总计(亿元)',
      //     totalRevenueBp: 0,
      //     totalRevenuerp: 0,
      //     totalRevenueM9: 0,
      //   }
      // );
      // totalRevenue.bpQuantity = (
      //   totalRevenue.totalRevenueBp / 100000000
      // ).toFixed(10);
      // totalRevenue.rpQuantity = (
      //   totalRevenue.totalRevenuerp / 100000000
      // ).toFixed(10);
      // totalRevenue.fcstQuantity = (
      //   totalRevenue.totalRevenueM9 / 100000000
      // ).toFixed(10);
      const data = [...list.flat(Infinity), smallAllTotal, ...this.total];
      data.forEach((item) => {
        if (item.id === 'totalKey') {
          if (!item.orderQuantity) {
            item.poRate = null;
          } else {
            item.poRate =
              ((item.orderQuantity / item.m9Quantity) * 100).toFixed(2) + '%';
          }
        }
      });
      return data;
    },
    groups() {
      return this.dataSource.reduce((pre, cur) => {
        if (pre[cur.salesGroupName]) {
          pre[cur.salesGroupName].push({ ...cur, id: ++idKey });
        } else {
          pre[cur.salesGroupName] = [{ ...cur, id: ++idKey }];
        }
        return pre;
      }, {});
    },
    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          width: 60,
          customRender(t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '销售组',
          dataIndex: 'salesGroupName',
          customRender: (value, row, index) => {
            return this.customRender(value, index, row, 'salesGroupName');
          },
        },
        {
          align: 'center',
          title: '客户简称',
          dataIndex: 'customerName',
          customRender: (value, row, index) => {
            return this.customRender(value, index, row, 'customerName');
          },
        },
        // {
        //   align: 'center',
        //   title: '应用别',
        //   dataIndex: 'application',
        //   customRender: (text) => this.applicationOptions[text],
        // },
        {
          align: 'center',
          title: '应用别',
          dataIndex: 'application',
          customRender: (value, row, index) => {
            return this.customRender(value, index, row, 'application');
          },
        },
        {
          align: 'center',
          title: `${this.month}月BP`,
          dataIndex: 'bpQuantity',
        },
        {
          align: 'center',
          title: `${this.month}月RP`,
          dataIndex: 'rpQuantity',
        },
        {
          align: 'center',
          title: `${this.month}月FCST`,
          dataIndex: 'm9Quantity',
        },
        {
          align: 'center',
          title: 'PO下达率(%)',
          dataIndex: 'poRate',
        },
        {
          align: 'center',
          title: '全国销量完成进度',
          dataIndex: 'quantity',
          children: [
            {
              align: 'center',
              title: 'MTD实际',
              dataIndex: 'mtd',
            },
            {
              align: 'center',
              title: '全月销售完成率%',
              dataIndex: 'sale',
            },
          ],
        },
      ];
      return columns;
    },
    totalalesGroupIndex() {
      return this.formatList.reduce((pre, cur, index) => {
        if (cur.id === 'totalKey') {
          pre.push(index);
        }
        return pre;
      }, []);
    },
    totalSmallAllTotalIndex() {
      return this.formatList.reduce((pre, cur, index) => {
        if (cur.id === 'smallAllTotal') {
          pre.push(index);
        }
        return pre;
      }, []);
    },
    totalBigAllIndex() {
      return this.formatList.reduce((pre, cur, index) => {
        if (cur.id === 'bigAllTotal') {
          pre.push(index);
        }
        return pre;
      }, []);
    },
    totalRevenueIndex() {
      return this.formatList.reduce((pre, cur, index) => {
        if (cur.id === 'totalRevenue') {
          pre.push(index);
        }
        return pre;
      }, []);
    },
  },
  created() {},
  methods: {
    customRender(children, index, row, key) {
      if (key === 'application') {
        children = this.applicationOptions[children];
      }
      console.log('key: ', key);
      const attrs = {};
      if (this.totalalesGroupIndex.includes(index)) {
        attrs.colSpan = 0;
      }
      if (this.totalSmallAllTotalIndex.includes(index)) {
        attrs.colSpan = 0;
      }
      if (this.totalBigAllIndex.includes(index)) {
        attrs.colSpan = 0;
      }
      if (this.totalRevenueIndex.includes(index)) {
        attrs.colSpan = 0;
      }
      if (key === 'salesGroupName') {
        const data = this.groups[row.salesGroupName] || [];
        if (row.id === data[0]?.id) {
          attrs.rowSpan = data.length;
        } else if (row.id === 'totalKey') {
          attrs.rowSpan = 1;
          attrs.colSpan = 3;
        } else if (row.id === 'smallAllTotal') {
          attrs.rowSpan = 1;
          attrs.colSpan = 3;
        } else if (row.id === 'bigAllTotal') {
          attrs.rowSpan = 1;
          attrs.colSpan = 3;
        } else if (row.id === 'totalRevenue') {
          attrs.rowSpan = 1;
          attrs.colSpan = 3;
        } else {
          attrs.rowSpan = 0;
        }
      }

      // if (key === 'application') {
      //   children = this.applicationOptions[children];
      //   if (row.id === 'totalKey') {
      //     attrs.colspan = 0;
      //   }
      // }

      // if (key === 'application' && row.id === 'totalKeyAll') {
      //   attrs.colSpan = 0;
      // }
      return {
        children,
        attrs,
      };
    },
  },
};
</script>

<style lang="less" scoped>
.table-list-container {
  margin-top: 20px;
}
</style>
